var socketIo = require('socket.io')
	, fs = require('fs');

var moment = require('moment');

var Model = require('../model');

var Message = Model.Message;
var Fans = Model.Fans;

/**
 * Expose Sockets initialization
 */

module.exports = Sockets;

/**
 * Socket.io
 *
 * @param {Express} app `Express` instance.
 * @param {HTTPServer} server `http` server instance.
 * @api public
 */

function Sockets (app, server) {

	var io = socketIo.listen(server);

	var config = app.get('config');

	var perpage = config.env.perpage;

	io.on('connection', function(socket){

		socket.on('send msg', function(param){

			var param = JSON.parse(param);

			Fans.findOne({ openid: param.openid }).exec(function (err, fans) {
				//代码生成自增id
				Message.findOne().sort({ unique_id: -1 }).exec(function (err, lastMsg) {

					var message = {
						unique_id: (!lastMsg)? 0: (lastMsg.unique_id + 1),
						fans: fans._id,
						message: param.msgText,
						created_at: moment().unix()
					};

					Message.create(message, function(err, msgRow){

						msgRow.fans = fans;

						var msgData = new Array(msgRow);

						io.emit('send msg', msgData);

					});
				});
			});
		});

		socket.on('load more', function(param){
			//console.log(param);

			Message.findById(param._id, function (err, firstMsg) {
				Message.find({ unique_id: { $lt: firstMsg.unique_id }})
					.populate('fans').sort({unique_id:-1}).limit(perpage+1).exec(function(err, msgData){
					socket.emit('load more', msgData);
				});
			});

		});
	});

}
